<template>
  <div>
    <el-card class="box-card" :body-style="{padding:'5px'}">
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-row v-if="!this.showcom">
          <el-col :span="7">
            <el-form-item label="组合代码" prop="combinationCode">
              <el-input v-model="form.combinationCode" placeholder="输入组合代码" :disabled="disableForm"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="组合名称" prop="combinationName">
              <el-input v-model="form.combinationName" placeholder="请输入组合名称" :disabled="disableForm"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="使用状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择状态">
                <el-option label="上架" value="1"></el-option>
                <el-option label="下架" value="0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!this.showcom">
          <el-col :span="22">
            <el-form-item label="简介" prop="briefIntroduction">
              <el-input
                v-model="form.briefIntroduction" placeholder="输入简介" :maxlength='15' :disabled="false"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!this.showcom">
          <el-col :span="22">
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}"
                        v-model="form.description" placeholder="输入描述" :maxlength='300' :disabled="false"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!this.showcom">
          <el-col :span="11">
            <el-form-item label="起购金额" prop="limitMoneyPurchased">
              <!--<el-select v-model="form.limitMoneyPurchased" placeholder="请选择起购金额">-->
              <!--<el-option label="一万" value="10000"></el-option>-->
              <!--<el-option label="五万" value="50000"></el-option>-->
              <!--<el-option label="十万" value="100000"></el-option>-->
              <!--<el-option label="二十万" value="200000"></el-option>-->
              <!--<el-option label="五十万" value="500000"></el-option>-->
              <!--</el-select>-->
              <el-input v-model="form.limitMoneyPurchased" placeholder="请选择起购金额" :disabled="false"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="基准年化(%)" prop="baseAnnualizedIncome">
              <el-input v-model="form.baseAnnualizedIncome" placeholder="输入基准年化" :disabled="false"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!this.showcom">
          <el-col :span="11">
            <el-form-item label="累计收益(%)" prop="accumulatedIncome">
              <el-col>
                <el-input v-model="form.accumulatedIncome" :disabled="false"/>
                <!--<el-date-picker type="date" placeholder="选择日期" v-model="form.createDate" style="width: 100%;"></el-date-picker>-->
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="年化收益(%)" prop="annualizedIncome">
              <el-input v-model="form.annualizedIncome" placeholder="输入设置资产值" :disabled="false"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!this.showcom">
          <el-col :span="11">
            <el-form-item label="运行天数" prop="runDay">
              <el-col>
                <el-input v-model="form.runDay" :disabled="false"/>
                <!--<el-date-picker type="date" placeholder="选择日期" v-model="form.createDate" style="width: 100%;"></el-date-picker>-->
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="日涨幅(%)" prop="dailyCent">
              <el-input v-model="form.dailyCent" placeholder="输入设置资产值" :disabled="false"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!this.showcom">
          <el-col :span="11">
            <el-form-item label="成立时间" prop="createDate">
              <el-col>
                <el-input v-model="form.createDate" :disabled="true"/>
                <!--<el-date-picker type="date" placeholder="选择日期" v-model="form.createDate" style="width: 100%;"></el-date-picker>-->
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="设置资产值" prop="baseCalculate">
              <el-input v-model="form.baseCalculate" placeholder="输入设置资产值" :disabled="disableForm"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="this.showcom">
          <el-col :span="7">
            <el-form-item label="基金代码" prop="fundCode">
              <el-input v-model="form.fundCode" placeholder="输入基金代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="基金份额(%)" prop="fundPercent">
              <el-input v-model="form.fundPercent" placeholder="输入基金份额"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收费类型" prop="fundShareType">
              <!--<el-input v-model="form.fundShareType" placeholder="输入收费类型:前端申购(A)后端申购(B)"/>-->
              <el-select v-model="form.fundShareType" placeholder="输入收费类型">
                <el-option label="前端申购" value="A"></el-option>
                <el-option label="后端申购" value="B"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="info" @click="saveHandler" :disabled="false">保存</el-button>
          <el-button type="danger" @click="backHandler" :disabled="false">返回</el-button>
        </el-form-item>


        <el-row v-if="this.showcom">
          <el-col :span="7">
            <el-form-item label="基金代码" prop="fundCode_edit">
              <el-input v-model="form.fundCode_edit" placeholder="输入基金代码" :disabled="editForm_on"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="基金份额(%)" prop="fundPercent_edit">
              <el-input v-model="form.fundPercent_edit" placeholder="输入基金份额" :disabled="editForm_on"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="this.showcom">
          <el-button type="info" @click="editHandler" :disabled="editForm_on">编辑</el-button>
          <el-button type="danger" @click="backHandler" :disabled="editForm_on">返回</el-button>
        </el-form-item>
      </el-form>

      <el-table v-if="this.showcom" :data="getCombination" border style="width: 100%" :highlight-current-row="true"
                @current-change="tableRowChangeClickHandler" current-row-key="id">
        <el-table-column fixed prop="fundCode" label="基金代码" min-width="50%"></el-table-column>
        <el-table-column prop="fundPercent" label="投资比例" min-width="40%"></el-table-column>
        <el-table-column inline-template label="操作" width="150">
          <template>
            <el-button type="danger" size="small" @click="deleteRow($index,row)">移除</el-button>
            <el-button type="success" size="small" @click="changeRow($index,row)">修改</el-button>
          </template>
        </el-table-column>

        <!--<el-table-column inline-template :context="_self" label="操作" width="100">-->
        <!--<span>-->
        <!--<el-button type="danger" size="small" @click="delInGridHandler($index,row)">Delete</el-button>-->
        <!--</span>-->
        <!--</el-table-column>-->
      </el-table>

    </el-card>
  </div>
</template>

<script type="text/babel">
  import assignDeep from 'assign-deep'
  import {mapActions, mapGetters} from 'vuex'
  import VueUeditor from 'vue-ueditor';
  import VueDraggable from 'vuedraggable'

  import fundPortfolioStore from './bll/fundPortfolioStore'
  import store from '../../store'

  (!store.state.sysfundPortfolio) && store.registerModule('sysfundPortfolio', fundPortfolioStore)

  export default {
    data() {
      return {
        disableForm: true,
        editForm_on: true,
        pageModel: 'ADD',
        callbacks: [],
        currentRecord: null,
        showcom: false,
        form: {
          combinationCode: '',
          combinationName: '',
          briefIntroduction: '',
          description: '',
          limitMoneyPurchased: '',
          baseAnnualizedIncome: '',
          createDate: '',
          fundCode: '',
          fundPercent: '',
          fundShareType: '',
          state: '',
          fundCode_edit: '',
          fundPercent_edit: '',
          mappingId_edit: '',
          accumulatedIncome: '',
          annualizedIncome: '',
          dailyCent: '',
          runDay: ''
        },
        rules: {
          briefIntroduction: [
            {required: true, message: '此项不能为空！'}
          ],
          description: [
            {required: true, message: '此项不能为空！'}
          ],
          limitMoneyPurchased: [
            {required: true, message: '此项不能为空！'}
          ],
          fundCode: [
            {required: true, message: '此项不能为空！'}
          ],
          fundPercent: [
            {required: true, message: '此项不能为空！'}
          ],
          fundShareType: [
            {required: true, message: '此项不能为空！'}
          ]
        }
      }
    },
    computed: {
      ...mapGetters(['getCombination'])
    },
    components: {VueUeditor, VueDraggable},
    props: {
      param: {
        type: Object
      },
      mode: {
        type: String
      }
    },

    watch: {
      param(record) {
        if (record) {
          this.form.combinationCode = record.combinationCode;
          this.form.combinationName = record.combinationName;
          this.form.briefIntroduction = record.briefIntroduction;
          this.form.description = record.description;
          this.form.limitMoneyPurchased = record.limitMoneyPurchased;
          this.form.baseAnnualizedIncome = record.baseAnnualizedIncome;
          this.form.createDate = record.createDate;
          this.form.baseCalculate = record.baseCalculate;
          this.form.state = record.state;
          this.form.fundCode = record.fundCode;
          this.form.fundPercent = record.fundPercent;
          this.form.fundShareType = record.fundShareType;
        } else {
          assignDeep(this.form, {
            combinationCode: '',
            combinationName: '',
            briefIntroduction: '',
            description: '',
            limitMoneyPurchased: '',
            baseAnnualizedIncome: '',
            createDate: '',
            baseCalculate: '',
            state: '',
            fundCode: '',
            fundPercent: '',
            fundShareType: ''
          });

        }
      },
      mode(val) {
        this.pageModel = val;
      }
    },

    mounted() {
      this.initPage();
    },

    methods: {
      ...mapActions(['editfiles', 'editFund', 'saveSysPortfolio', 'updateSysPortfolio', 'queryPortfolio', 'queryCombination', 'saveSysCombination', 'deleteSysCombination']),
      saveHandler() {
        let self = this;
        console.log(1)
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (self.$route.query.type) {
              self.form.fundCombinationCode = this.$route.query.combinationCode
              self.saveSysCombination(self.form).then(() => {
                self.$alert('组合添加成功', '消息', {
                  confirmButtonText: '确认'
                }).then(() => {
                  const combinationCode = this.$route.query.combinationCode;
                  //const type = this.$route.query.type;
                  this.queryCombination({combinationCode})
                });
              })
            } else {
              if (self.form.state === '下架') {
                self.form.state = 0
              } else if (self.state === '上架') {
                self.form.state = 1
              }
              self[self.pageModel === 'ADD' ? 'saveSysPortfolio' : 'updateSysPortfolio'](self.form).then(() => {
                self.disable();
                if (self.pageModel === 'ADD') {
                  self.$confirm('添加成功', '信息', {
                    cancelButtonText: '返回列表',
                    type: 'info'
                  }).then(() => {
                    self.$router.push('/fundPortfolio/index');
                  }).catch(() => {
                    self.$router.push('/fundPortfolio/index');
                  });
                } else {
                  self.$alert('组合修改成功', '消息', {
                    confirmButtonText: '确认'
                  }).then(() => {
                    self.$router.push('/fundPortfolio/index');
                  });
                }
              })
            }
            console.log(2)
          } else {
            this.$message({
              showClose: true,
              message: 'Please check this form information.',
              type: 'error'
            });

            return false;
          }
        });
      },
      editHandler() {
        this.$confirm('确定修改, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var mappingId = this.form.mappingId_edit
          this.editFund({mappingId: mappingId, fundPercent: this.form.fundPercent_edit}).then(() => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            const combinationCode = this.$route.query.combinationCode;
            //const type = this.$route.query.type;
            this.queryCombination({combinationCode})
            this.editForm_on = true
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          });
        });
      },
      resetHandler() {
        this.enable();
        this.editor.setContent('');
        this.$refs.form.resetFields();
      },
      backHandler() {
        this.$router.push('/fundPortfolio/index');
      },
      deleteRow(index, row) {
        console.log(row)
        console.log(index)
//        if (!this.currentRecord) {
//          this.$message.warning('Please select one record.');
//          return;
//        }
        this.$confirm('确定删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var mappingId = row.mappingId
          this.deleteSysCombination({mappingId}).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            const combinationCode = this.$route.query.combinationCode;
            //const type = this.$route.query.type;
            this.queryCombination({combinationCode})
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      changeRow(index, row) {
        console.log(row)
        console.log(index)
        this.editForm_on = false
        var mappingId = row.mappingId
        var self = this
        this.editfiles({mappingId: mappingId}).then((data) => {
          console.log(data)
          self.form.fundCode_edit = data.fundCode
          self.form.fundPercent_edit = data.fundPercent
          self.form.mappingId_edit = data.mappingId
        }
        )

      },
      tableRowChangeClickHandler(currentRow, oldCurrentRow) {
        console.log(currentRow);
        this.currentRecord = currentRow;
//        this.form.fundCode_edit = currentRow.fundCode
//        this.form.fundPercent_edit = currentRow.fundPercent
        this.editForm = true
      },
      initPage() {
        if (this.$route.query.type === 'combination') {
          this.showcom = true
        }
        this.enable()
        if (this.$route.query) {
          const combinationCode = this.$route.query.combinationCode;
          const type = this.$route.query.type;
          console.log(combinationCode)
          if (type) {
            this.queryCombination({combinationCode})
          } else if (combinationCode) {
            this.disable()
            this.pageModel = 'EDIT'
            this.queryPortfolio({combinationCode}).then(Portfolio => {
              console.log(Portfolio);
              if (Portfolio.state === 0) {
                Portfolio.state = '下架'
              } else if (Portfolio.state === 1) {
                Portfolio.state = '上架'
              }
              this.form = Portfolio;
              //this.editor.setContent(this.form.content);
              this.getEditorReady(() => {
                this.editor.setContent(this.form.content);
              });
            });

          }

        }
      },

      getEditorReady(cb) {
        if (this.editor) {
          this.editor.ready(cb);
        } else {
          this.callbacks.push(cb);
        }
      },


      // interface for invoking

      disable() {
        this.disableForm = true;
      },
      enable() {
        this.disableForm = false;
      },
      clear() {
        this.$refs.form.resetFields();
      }
    }
  }
</script>
